import router from '@/router'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { BASE_URL, BASE_PREFIX, TOKEN_NAME } from '@/config/constants'

const request = axios.create({
  baseURL: BASE_URL + BASE_PREFIX,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem(TOKEN_NAME);
    (config as any).headers.Authorization = token
    const ticket = router.currentRoute.value.query.ticket
    if (ticket) {
      (config as any).headers.ticket = ticket
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data
    if (!data) {
      throw new Error('请求接口错误')
    }
    const { code, msg } = data

    if (code === '200') {
      return data.data
    }
    throw new Error(msg)
  },
  (error: any) => {
    if (error.response.status === 401) {
      // 认证失败，跳转到登录页面
      router.push({
        name: 'login'
      })
    } else if (error.response.status === 403) {
      router.push({
        name: 'not-fount'
      })
    } else {
      throw new Error(error.response.message || '接口返回异常')
    }
  }
)

export default request
